package com.lagou.rocketmq.producer;

import com.lagou.enums.DelayLevelEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @ClassName: Producer
 * @Description:
 * @Author: qjc
 * @Date: 2021/12/21 2:25 下午
 */
@Component
@Slf4j
public class Producer {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    /**
     * 发送普通消息
     */
    public Boolean pushMessage(String topic, String tag, Long content) {
        try {
            rocketMQTemplate.convertAndSend(topic + ":" + tag, content);
        } catch (MessagingException e) {
            log.error("发送消息出现异常");
            return false;
        }
        return true;
    }

    /**
     * 发送延时消息
     */
    public Boolean pushDelayMessage(String topic, String tag, Long content, DelayLevelEnum delayTimeLevel) {
        try {
            Message<Long> message = MessageBuilder.withPayload(content)
                    .build();
            rocketMQTemplate.syncSend(topic + ":" + tag, message, 1_000, delayTimeLevel.getLevel());
        } catch (MessagingException e) {
            log.error("发送消息出现异常");
            return false;
        }
        return true;
    }


}
